<template>
  <div class="init_main">
    <p class="name_sty">{{ name }}</p>
    <div class="query">
      *科室：
      <el-select
        v-model="query.sectionId"
        filterable
        placeholder=""
        clearable
        size="mini"
      >
        <el-option
          :label="item.Name"
          :value="item.Id"
          v-for="item in SectionsList"
          :key="item.Id"
        >
        </el-option>
      </el-select>
      *起始日期：
      <el-date-picker
        size="mini"
        v-model="query.dateStart"
        format="yyyy 年 MM 月 dd 日"
        value-format="yyyy-MM-dd"
        type="date"
        placeholder="选择日期"
      >
      </el-date-picker>
      *结束日期：
      <el-date-picker
        size="mini"
        v-model="query.dateEnd"
        format="yyyy 年 MM 月 dd 日"
        value-format="yyyy-MM-dd"
        type="date"
        placeholder="选择日期"
      >
      </el-date-picker>
      <el-button
        plain
        size="mini"
        icon="el-icon-search"
        style="margin-left: 10px"
        @click="getList"
        >查询</el-button
      >
      <el-button
        plain
        size="mini"
        style="margin-left: 10px"
        @click="getnexkweek"
        title="注意，复制排班建议只操作一周数据！"
        >复制到下周排班</el-button
      >
      <span style="color: red; margin-left: 10px"
        >增加/删除排班请双击单元格操作</span
      >
      <!-- <el-button
        plain
        size="mini"
        icon="el-icon-plus"
        type="primary"
        @click="open_dialog('新增')"
        >新增</el-button
      > -->
      <!-- <el-button
        plain
        size="mini"
        icon="el-icon-edit"
        type="primary"
        @click="open_dialog('修改')"
        >修改</el-button
      >
      <el-button
        plain
        size="mini"
        icon="el-icon-delete"
        type="danger"
        @click="del_row"
        >删除</el-button
      > -->
    </div>
    <div class="table">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        height="600"
        highlight-current-row
        @current-change="row_click"
        @cell-dblclick="cell_click"
        v-if="isNowShow"
      >
        <!-- <el-table-column prop="Type" label="类型" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.Type | to_type }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="UserName"
          label="姓名"
          align="center"
          fixed
          width="120"
        >
        </el-table-column>
        <el-table-column
          v-for="(col, index) in tableColumns"
          :key="index"
          :label="col.label"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <div class="cell-content">
              <span v-for="(item2, index2) in scope.row.List" :key="index2">
                <span v-if="item2.Date == tableColumns[index].value">
                  <div
                    v-for="(item3, index3) in scope.row.List[index2].List"
                    :key="index3"
                  >
                    <p
                      style="font-size: 12px; color: #fff; margin: 0"
                      :style="
                        'background:' +
                        scope.row.List[index2].List[index3].Color
                      "
                      v-if="scope.row.List[index2].List[index3].Color"
                    >
                      {{ scope.row.List[index2].List[index3].CategoryName }}({{
                        scope.row.List[index2].List[index3].Name
                      }})
                    </p>
                    <p
                      style="font-size: 12px; margin: 0"
                      :style="
                        'background:' +
                        scope.row.List[index2].List[index3].Color
                      "
                      v-else
                    >
                      {{ scope.row.List[index2].List[index3].CategoryName }}({{
                        scope.row.List[index2].List[index3].Name
                      }})
                    </p>
                  </div>
                </span>
              </span>
              <!-- {{ scope.row.List[0].Date }} -->
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="Color" label="颜色" align="center">
          <template slot-scope="scope">
            <span
              class="color_box"
              :style="'backgroundColor:' + scope.row.Color"
            ></span>
          </template>
        </el-table-column> -->
      </el-table>
    </div>
    <!-- <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange_page"
        :current-page="query.CurrentPage"
        :page-sizes="[10, 15, 50, 100]"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="query.total"
      >
      </el-pagination>
    </div> -->
    <!-- 弹层 -->
    <el-dialog
      :title="dialog_title"
      :visible.sync="dialogVisible"
      width="45%"
      :before-close="handleClose"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <table border="1" style="width: 100%" v-if="dialogVisible">
        <tr>
          <td class="tac">日期：</td>
          <td>
            <el-date-picker
              size="mini"
              v-model="form.date"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            >
            </el-date-picker>
          </td>
        </tr>
        <tr>
          <td class="tac">分类：</td>
          <td>
            <el-select
              v-model="form.type"
              style="width: 100%"
              placeholder=""
              size="mini"
              @change="getNameList"
            >
              <el-option label="白班" value="1"> </el-option>
              <el-option label="夜班" value="2"> </el-option>
              <el-option label="请假" value="3"> </el-option>
              <el-option label="休息" value="4"> </el-option>
              <el-option label="公休假" value="5"> </el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td class="tac">排班：</td>
          <td>
            <el-select
              v-model="form.categoryId"
              style="width: 100%"
              placeholder=""
              size="mini"
            >
              <el-option
                :label="item4.Name"
                :value="item4.Id"
                v-for="item4 in nameList"
                :key="item4.Id"
              >
              </el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td class="tac">备注：</td>
          <td>
            <el-input size="mini" v-model="form.name"></el-input>
          </td>
        </tr>
      </table>
      <div>
        <p>当日班次</p>
        <el-tag
          v-for="tag in isNowBC"
          :key="tag.Id"
          closable
          @close="del_row(tag)"
          style="margin-right: 10px"
        >
          {{ tag.CategoryName }}（{{ tag.Name }}）
        </el-tag>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" size="mini">关 闭</el-button>
        <el-button type="primary" @click="btn_ok" size="mini">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "",
      query: {
        sectionId: "",
        dateStart: "",
        dateEnd: "",
      },
      tableData: [],
      dialogVisible: false,
      dialog_title: "",
      row_info: null,
      form: {
        userId: "",
        sectionId: "",
        date: "",
        categoryId: "",
        name: "",
      },
      userList: [],
      SectionsList: [],
      tableColumns: [],
      weekMap: {
        0: "周日",
        1: "周一",
        2: "周二",
        3: "周三",
        4: "周四",
        5: "周五",
        6: "周六",
      },
      nameList: [],
      isNowBC: [],
      isNowShow: true,
    };
  },
  mounted() {
    this.name = this.$route.meta.title;
    // this.getList();
    this.getSections();
  },
  filters: {
    to_type(val) {
      var str = "";
      if (val == 1) {
        str = "白班";
      }
      if (val == 2) {
        str = "夜班";
      }
      if (val == 3) {
        str = "请假";
      }
      if (val == 4) {
        str = "休息";
      }
      if (val == 5) {
        str = "公休假";
      }
      return str;
    },
  },
  methods: {
    getSections() {
      this.$get("/Schedule/Sections").then((res) => {
        this.SectionsList = res.Data;
      });
    },
    getList() {
      this.isNowShow = false;
      this.tableData = [];
      this.$post("/Schedule/GetWeekList", this.query).then((res) => {
        this.tableData = res.Data;
        this.$nextTick((_) => {
          this.generateTableColumns();
        });
      });
    },
    getNameList(val) {
      var body = {
        type: val,
      };
      this.$post("/ScheduleCategory/GetAll", body).then((res) => {
        this.nameList = res.Data;
      });
    },
    generateTableColumns() {
      const dateRange = this.getDateRange(
        this.query.dateStart,
        this.query.dateEnd
      );
      this.tableColumns = dateRange.map((date) => {
        const weekDay = this.getWeekDay(date);

        return {
          property: date.replace(/-/g, ""),
          label: `${date}  ${weekDay}`,
          value: `${date}`,
        };
      });
      this.isNowShow = true;
    },
    getUserList() {
      this.$post("/Bs/GetAllUserList").then((res) => {
        this.userList = res.Data;
      });
    },
    open_windo(url) {
      window.open(url);
    },
    row_click(row) {
      if (!row) {
        this.row_info = null;
        return;
      }
      var srt = JSON.stringify(row);
      this.row_info = JSON.parse(srt);
    },
    cell_click(row, column, cell, event) {
      var date = this.extractDate(column.label);
      this.isDialog_title_date = column.label;
      this.open_dialog(date);
    },
    extractDate(dateStr) {
      // 使用正则表达式匹配日期格式 YYYY-MM-DD
      const dateRegex = /(\d{4})-(\d{1,2})-(\d{1,2})/;
      const match = dateStr.match(dateRegex);

      if (match && match.length >= 4) {
        // 组合年、月、日，确保月和日为两位数字
        const year = match[1];
        const month = String(match[2]).padStart(2, "0");
        const day = String(match[3]).padStart(2, "0");
        return `${year}-${month}-${day}`;
      }

      // 如果匹配失败，返回原始字符串或空字符串
      console.warn("无法提取日期，输入格式不符合要求");
      return dateStr;
    },

    del_row(val) {
      this.$confirm(
        "当前正在进行删除班次操作，删除班次为：" +
          val.CategoryName +
          "（" +
          val.Name +
          "）",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$get("/Schedule/Remove?id=" + val.Id).then((res) => {
            if (res.StatusCode != 200) {
              this.$notify.error({
                title: "错误",
                message: res.Errors,
              });
              return;
            }
            this.getList();
            this.handleClose();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {});
      console.log(val);
      //   this.$get("/ScheduleCategory/SoftDelete/" + this.row_info.Id).then(
      //     (res) => {
      //       this.getList();
      //     }
      //   );
    },
    handleClose() {
      this.form = {};
      this.dialogVisible = false;
    },
    btn_ok() {
      console.log(this.form);
      this.$post("/Schedule/Add", this.form).then((res) => {
        if (res.StatusCode != 200) {
          this.$notify.error({
            title: "错误",
            message: res.Errors,
          });
          return;
        }
        this.getList();
        this.handleClose();
      });
    },
    open_dialog(val) {
      this.isNowBC = [];
      console.log(val);
      console.log(this.row_info);
      this.dialog_title = this.row_info.UserName + "，" + val + "排班";
      this.form.userId = this.row_info.UserId;
      this.form.sectionId = this.row_info.SectionId;
      this.form.date = val;
      for (var i in this.row_info.List) {
        if (this.row_info.List[i].Date == val) {
          this.isNowBC = this.row_info.List[i].List;
        } else {
          // this.isNowBC = [];
        }
      }
      this.dialogVisible = true;
    },
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.query.CurrentPage = 1;
    },
    handleCurrentChange_page(val) {
      this.query.CurrentPage = val;
      this.getList();
    },
    setUserName(id) {
      console.log(id);
    },
    getDateRange(startDate, endDate) {
      const dates = [];
      const start = new Date(startDate);
      const end = new Date(endDate);

      let currentDate = new Date(start);
      while (currentDate <= end) {
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, "0");
        const day = String(currentDate.getDate()).padStart(2, "0");
        dates.push(`${year}-${month}-${day}`);

        // 移动到下一天
        currentDate = new Date(currentDate.setDate(currentDate.getDate() + 1));
      }

      return dates;
    },

    // 获取日期对应的星期
    getWeekDay(dateStr) {
      const date = new Date(dateStr);
      const weekDay = date.getDay().toString();
      return this.weekMap[weekDay] || "未知";
    },

    // 准备示例数据

    // 表头样式
    headerCellStyle({ row, column, rowIndex, columnIndex }) {
      return "date-header";
    },
    getnexkweek() {
      this.$post("/Schedule/HasNextWeek", this.query).then((res) => {
        if (res.Data == true) {
          this.$confirm(
            "复制的目标的天里已存在创建过排班，是否继续覆盖?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.setnexkweek();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消操作",
              });
            });
        } else {
          this.setnexkweek();
        }
      });
    },
    setnexkweek() {
      this.$post("/Schedule/CopyToNextWeek", this.query).then((res) => {
        this.$message({
          type: "success",
          message: "操作成功!",
        });
      });
    },
  },
};
</script>

<style scoped lang='scss'>
.init_main {
  background-color: #fff;
  height: calc(100vh - 60px);
  border: 1px solid #333;
  border-radius: 5px;
  margin: 5px;
  padding: 10px;
  font-family: "FangSong";
  color: #000;
  -webkit-user-select: none; /* Safari、Chrome等webkit内核浏览器 */
  -moz-user-select: none; /* Firefox浏览器 */
  -ms-user-select: none; /* IE 10+ 和 Edge浏览器 */
  user-select: none; /* 支持该属性的其他现代浏览器 */
  .name_sty {
    color: #000;
    font-weight: 700;
    font-size: 18px;
    font-family: "FangSong";
    border-bottom: 1px solid #333;
    padding-bottom: 5px;
  }
  .table {
    margin-top: 15px;
  }
  .page {
    text-align: right;
  }
}
::v-deep .el-table__body tr.current-row > td.el-table__cell {
  background-color: rgb(208, 229, 250);
  color: rgb(65, 158, 255);
  font-weight: 700;
}
.tac {
  text-align: center;
}
.color_box {
  display: inline-block;
  width: 20px;
  height: 15px;
  border: 1px solid #000;
}
::v-deep .el-table .cell {
  padding: 0;
}
</style>